package com.lzp.java.jdk8.lambda.c4;

import com.lzp.java.jdk8.lambda.pojo.Album;
import com.lzp.java.jdk8.lambda.pojo.Artist;
import com.lzp.java.jdk8.lambda.pojo.Track;

import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Optional;

/**
 * @description: 多个艺术家
 * @author: lzp
 * @createTime: 2021-07-18 15:25
 **/
public class Artists {
    private List<Artist> artists;

    public Artists(List<Artist> artists) {
        this.artists = artists;
    }

    public Artist getArtist(int index) {
        if (index < 0 || index >= artists.size()) {
            throw new IllegalArgumentException("参数越界");
        }
        return artists.get(index);
    }

    public String getArtistName(int index) {
        try {
            Artist artist = getArtist(index);
            return artist.getName();
        } catch (IllegalArgumentException e) {
            return "unknown";
        }
    }

    /*使用Optional避免null*/

    public Optional<Artist> getArtistByOptional(int index) {
        if (index < 0 || index >= artists.size()) {
            return Optional.empty();
        }
        return Optional.of(artists.get(index));
    }

    public String getArtistNameByOptional(int index) {
        Optional<Artist> artist = getArtistByOptional(index);
        return artist.map(Artist::getName).orElse("unknown");
    }

    public static void printTrackLengthStatics(Album album) {
        IntSummaryStatistics statistics = album.getTracks()
                .mapToInt(Track::getLength)
                .summaryStatistics();
        System.out.println(statistics.getMax());
        System.out.println(statistics.getCount());
        System.out.println(statistics.getAverage());
    }
}

